package com.google.gwt.livinglife.client.widgets;

import com.google.gwt.core.client.GWT;
import com.google.gwt.livinglife.client.LivingLife;
import com.google.gwt.livinglife.client.LivingLifeService;
import com.google.gwt.livinglife.client.LivingLifeServiceAsync;
import com.google.gwt.livinglife.client.LoginInfo;
import com.google.gwt.livinglife.client.NotLoggedInException;
import com.google.gwt.livinglife.client.data.ChallengeData;
import com.google.gwt.livinglife.client.data.ResponseData;
import com.google.gwt.livinglife.client.data.UserIdData;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class ResponseEntryForm extends BasicEntryForm {
	Long challenge_id;
	ChallengeBox parent_box;
	
	@Override
	public void handleSubmit() {
		final ResponseData response_data = new ResponseData();
		FillBasicPost(response_data);
		LoginInfo login_info = LivingLife.getLogin_info();
		if (login_info == null || login_info.getUser_data() == null) {
			Window.alert("Please sign in");
			return;
		}
		response_data.setAuthor(new UserIdData(login_info.getUser_data()));
		response_data.setChallenge(challenge_id);
		LivingLifeServiceAsync service = GWT.create(LivingLifeService.class);
			try {
				service.addResponse(response_data, new AsyncCallback<Long>(){

					@Override
					public void onFailure(Throwable caught) {
						Window.alert("Network error while adding response to the challenge. Please try at a later time.");
					}
					@Override
					public void onSuccess(Long result) {
						response_data.setId(result);
						parent_box.AddResponseData(response_data);
						parent_box.removeResponseForm();
					}
				});
			} catch (NotLoggedInException e) {
				Window.alert("Please sign-in first.");
			}
	}

	public Long getChallenge_id() {
		return challenge_id;
	}

	public void setChallenge_id(Long challengeId) {
		challenge_id = challengeId;
	}

	public ChallengeBox getParent_box() {
		return parent_box;
	}

	public void setParent_box(ChallengeBox parentBox) {
		parent_box = parentBox;
	}
}
